#include "plateau.h"

#include "case.h"

#include <QtCore/QDebug>

Plateau::Plateau() {
	m_cases.resize(12);
	for (int i = 0; i < 12; ++i)
		m_cases[i] = new Case(i);

	int nbGraines = 0;
	foreach (Case* c, m_cases)
		nbGraines += c->nbGraines();
}

Plateau::Plateau(const Plateau &pSource) {
	*this = pSource;
}

Plateau::~Plateau() {
	foreach (Case* c, m_cases)
		delete c;
	m_cases.clear();
}

Plateau& Plateau::operator=(const Plateau& pSource) {
	foreach (Case* c, m_cases)
		delete c;
	m_cases.clear();

	m_cases.resize(12);
	for (int i = 0; i < 12; ++i) {
		m_cases[i] = new Case(*pSource.m_cases[i]);
	}
	return *this;
}

bool Plateau::operator==(const Plateau& pAutre) const {
	for (int i = 0; i < m_cases.size(); ++i) {
		if (m_cases[i]->nbGraines() != pAutre.m_cases[i]->nbGraines())
			return false;
	}
	return true;
}

bool Plateau::operator!=(const Plateau& pAutre) const {
	return !(*this == pAutre);
}

bool Plateau::termine() const {
	int nbGraines = 0;
	foreach (Case* c, m_cases)
		nbGraines += c->nbGraines();

	return (nbGraines > 6 ? false : true);
}

int Plateau::simulerCoup(int pPos, Plateau &pEtatFinal) const {
	pEtatFinal = *this;
	int numJoueur = pEtatFinal.m_cases[pPos]->numJoueur();
	int nbPrises = 0;

	int nbGraines = pEtatFinal.m_cases[pPos]->nbGraines();
	pEtatFinal.m_cases[pPos]->setNbGraines(0);
	int k;
	for (k = pPos + 1; k <= nbGraines + pPos; ++k) {
		int numCase = k % 12;
		if (numCase != pPos)
			pEtatFinal.m_cases[numCase]->setNbGraines(pEtatFinal.m_cases[numCase]->nbGraines() + 1);
		else
			nbGraines++;
	}
	--k;

	if (k <= 0)
		k += 12;
	k %= 12;

	// k vaut maintenant la position d'arrivée
	while (pEtatFinal.m_cases[k]->numJoueur() != numJoueur && (pEtatFinal.m_cases[k]->nbGraines() == 2 || pEtatFinal.m_cases[k]->nbGraines() == 3)) {
		nbPrises += pEtatFinal.m_cases[k]->nbGraines();
		pEtatFinal.m_cases[k]->setNbGraines(0);
		if (k <= 0)
			k += 12;
		k = (k - 1) % 12;
	}
	return nbPrises;
}

int Plateau::jouerCoup(int pPos) {
	Plateau etatFinal;
	int nbPrises = simulerCoup(pPos, etatFinal);
	operator=(etatFinal);
	return nbPrises;
}
